package com.jackrain.nea.omslocal.service;/**
 * Created by Administrator on 2017/3/28.
 */

import com.alibaba.dubbo.common.utils.NetUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.aliyun.mns.model.TopicMessage;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.util.ApplicationContextHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description:
 * Created with IntelliJ IDEA.
 * User: cs
 * Date: 2017/3/28
 * Time: 10:05
 */

@Component
@Slf4j
public class SendMqServies {

    @Autowired
    private PropertiesConf pconf;
    @Autowired
    private ProducerBean producerBean;
    @Autowired
    private LocalLogService localLogService;
    @Autowired
    private SaveAllMsgService saveFailedMsgService;

    private FastDateFormat fastformat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    /**
     * 发送jsonObj 类型消息
     * @param dataobject
     * @param topic
     * @param ctag
     * @throws Exception
     */
    public String sendMqinfoObj(JSONObject dataobject, String topic, String ctag) {


        if (ctag.equalsIgnoreCase("err") && dataobject.getString("errmsg") != null) {
            sendSMS(dataobject);
        }
        Message msg = null;
        String msgId=null;
        String str = UUID.randomUUID().toString();
        try {
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(dataobject));
            msg.setKey(str);
            SendResult sendResult = producerBean.send(msg);
            assert sendResult != null;
            msgId = sendResult.getMessageId();
            if (msgId == null || msgId.equals("") ){
                // 消息发送失败
                return "-1";
            }

            //localLogService.saveSendMsg();
            log.debug("send success : MSGID[" + str + "] ---" + topic + "========" + ctag);

        } catch (ONSClientException e) {
            // 消息发送失败,保存到 临时表,以任务发送
            if (pconf.getProperty("ons.qtyunorderTopic").equals(topic)){
                // 是库存消息发送失败时不保存,延时 1秒 再发送
                log.debug("同步库存数据发送失败" );
            }
            return "-1";
            //saveFailedMsgService.saveFailedMsg(dataobject,topic,ctag);

        }catch (Exception i){
            // 序列化,流错误
            log.debug("序列化错误,消息发送失败");
            return "-1";
            //saveFailedMsgService.saveFailedMsg(dataobject,topic,ctag);
        }
        return msgId;
    }

    /**
     * 发送短信
     * @param senderContext
     */
    public void sendSMS(JSONObject senderContext) {
        String accessKey = pconf.getProperty("lons.accessKey");
        String secretKey = pconf.getProperty("ons.secretKey");
        String Endpoint = pconf.getProperty("ons.mnsendpoint");
        String mnstopic = pconf.getProperty("ons.mnstopic");
        String smsphone = pconf.getProperty("oms.smsphone");
        String smstemp = pconf.getProperty("oms.smstemp");
        String company = pconf.getProperty("ons.comp");
        String sing = pconf.getProperty("ons.sign");

        /**
         * Step 1. 获取主题引用
         */
        CloudAccount account = new CloudAccount(accessKey, secretKey, Endpoint);
        MNSClient client = account.getMNSClient();
        CloudTopic topic = client.getTopicRef(mnstopic);
        /**
         * Step 2. 设置SMS消息体（必须）
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
        RawTopicMessage msg = new RawTopicMessage();
        msg.setMessageBody("sms-message");
        /**
         * Step 3. 生成SMS消息属性
         */
        MessageAttributes messageAttributes = new MessageAttributes();
        BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
        // 3.1 设置发送短信的签名（SMSSignName）
        batchSmsAttributes.setFreeSignName(sing);
        // 3.2 设置发送短信使用的模板（SMSTempateCode）
        batchSmsAttributes.setTemplateCode(smstemp);
        // 3.3 设置发送短信所使用的模板中参数对应的值（在短信模板中定义的，没有可以不用设置）
        BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
        smsReceiverParams.setParam("company", company);
        smsReceiverParams.setParam("errmsg", shorten(senderContext.getString("errmsg"), 50, "..."));
        smsReceiverParams.setParam("protime", fastformat.format(System.currentTimeMillis()));
        smsReceiverParams.setParam("clientip", NetUtils.getLocalAddress().getHostAddress().replace(".", "-"));
        // 3.4 增加接收短信的号码

        if (smsphone.trim().indexOf(",") > 0) {
            String[] phones = smsphone.split(",");
            for (int i = 0; i < phones.length; i++) {
                System.out.println(phones[i]);
                batchSmsAttributes.addSmsReceiver(phones[i], smsReceiverParams);
            }
        } else {
            batchSmsAttributes.addSmsReceiver(smsphone, smsReceiverParams);
        }
        //batchSmsAttributes.addSmsReceiver(smsphone, smsReceiverParams);
        //batchSmsAttributes.addSmsReceiver("18818200818", smsReceiverParams);
        //batchSmsAttributes.addSmsReceiver("$YourReceiverPhoneNumber2", smsReceiverParams);
        messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
        try {
            /**
             * Step 4. 发布SMS消息
             */
            TopicMessage ret = topic.publishMessage(msg, messageAttributes);
            System.out.println("MessageId: " + ret.getMessageId());
            System.out.println("MessageMD5: " + ret.getMessageBodyMD5());
        } catch (ServiceException se) {
            System.out.println(se.getErrorCode() + se.getRequestId());
            System.out.println(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        client.close();
    }


    /**
     * length will include suffix's length, for instance,
     * shorten("abcd", 3, "..") = "a.."
     */
    public static String shorten(String s, int length, String suffix) {
        if (s == null || suffix == null) {
            return null;
        }

        if (s.length() > length) {
            s = s.substring(0, length - suffix.length()) + suffix;
        }

        return s;
    }

    public SendResult sendMqObj(JSONObject dataobject, String topic, String ctag) throws Exception {

        Message msg = null;
        msg = new Message(topic, ctag, MsgConvertUtil.objectSerialize(dataobject));
        String str = UUID.randomUUID().toString();
        msg.setKey(str);

        //获取本身bean发送
        SendResult sendResult = ApplicationContextHandle.getBean(SendMqServies.class).send(msg);

        if (sendResult != null) {
            log.debug("send success: " + sendResult.getMessageId() + topic);
        }


        return sendResult;
    }

    public SendResult sendMqRetLogObj(JSONObject dataobject, String topic, String ctag,String sellerNick) throws Exception {
        PropertiesConf propertiesConf = ApplicationContextHandle.getBean(PropertiesConf.class);
        String jdLogErrTopic = propertiesConf.getProperty("ons.jdLogErrTopic","");
        Message msg = null;
        SendResult sendResult = null;
        try {
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(dataobject));
            String str = UUID.randomUUID().toString();
            msg.setKey(str);
            //获取本身bean发送
            sendResult = producerBean.send(msg);

            if (sendResult != null) {
                log.debug("send success: " + sendResult.getMessageId() + topic);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject errLogObject = new JSONObject();
            errLogObject.put("flag",0);
            errLogObject.put("errmsg", "消息发送失败");
            errLogObject.put("topic", topic);
            errLogObject.put("tag", ctag);
            errLogObject.put("ip", NetUtils.getLocalAddress());
            errLogObject.put("sellernick", sellerNick);
            sendMqObj(errLogObject,jdLogErrTopic,ctag);
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(dataobject));
            String str = UUID.randomUUID().toString();
            msg.setKey(str);
            //获取本身bean发送
            sendResult =  producerBean.send(msg);

            if (sendResult != null) {
                log.debug("send success:" + sendResult.getMessageId() + topic);
            }
        }
        return sendResult;
    }


    public SendResult sendMqLogRetArr(JSONArray jsonArray, String topic, String ctag) throws Exception {


        PropertiesConf propertiesConf = ApplicationContextHandle.getBean(PropertiesConf.class);
        String jdLogErrTopic = propertiesConf.getProperty("ons.jdLogErrTopic","");
        Message msg = null;
        SendResult sendResult = null;
        try {
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(jsonArray));
            String str = UUID.randomUUID().toString();
            msg.setKey(str);
            //获取本身bean发送
            sendResult = producerBean.send(msg);

            if (sendResult != null) {
                log.debug("send success:" + sendResult.getMessageId() + topic);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject errLogObject = new JSONObject();
            errLogObject.put("flag",0);
            errLogObject.put("errmsg", "消息发送失败");
            errLogObject.put("topic", topic);
            errLogObject.put("tag", ctag);
            errLogObject.put("ip", NetUtils.getLocalAddress());
            sendMqObj(errLogObject,jdLogErrTopic,ctag);
            msg = new Message(topic, ctag, MsgConvertUtil
                    .objectSerialize(jsonArray));
            String str = UUID.randomUUID().toString();
            msg.setKey(str);
            //获取本身bean发送
            sendResult =  producerBean.send(msg);

            if (sendResult != null) {
                log.debug("send success:" + sendResult.getMessageId() + topic);
            }
        }
        return sendResult;
    }


    public SendResult send(Message msg){
        log.debug("sended");

        return producerBean.send(msg);
    }

    /**
     * 发送消息
     *
     * @param dataarry
     * @param ctag
     * @throws Exception
     */
    public SendResult sendMqArr(JSONArray dataarry, String topic, String ctag) throws Exception {


        Message msg = null;
        //  Expr 就是 tag
        msg = new Message(topic, ctag, MsgConvertUtil
                .objectSerialize(dataarry));
        String str = UUID.randomUUID().toString();
        msg.setKey(str);

        //获取本身bean
        SendResult sendResult = ApplicationContextHandle.getBean(SendMqServies.class).send(msg);

        if (sendResult != null) {
            log.debug("send  success: " + sendResult.getMessageId() + topic);
        }

        return sendResult;

    }
}
